package com.yxw.live_vod_boot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.live_vod_backend_facade.dto.NoticeTypeQueryDto;
import com.yxw.live_vod_backend_facade.feign.SysNoticeFeignClient;
import com.yxw.live_vod_backend_facade.vo.NoticeTypeVo;
import com.yxw.live_vod_boot.dto.ReviewExamineDTO;
import com.yxw.live_vod_boot.dto.SendInteractMsgDto;
import com.yxw.live_vod_boot.dto.SendNormalMsgDto;
import com.yxw.live_vod_boot.dto.SysNoticeQueryDTO;
import com.yxw.live_vod_boot.entity.YxSysNoticeEntity;
import com.yxw.live_vod_boot.entity.YxUploadSourceMaterialReviewEntity;
import com.yxw.live_vod_boot.enums.MqttTopicEnum;
import com.yxw.live_vod_boot.mapper.ShopMapper;
import com.yxw.live_vod_boot.mapper.SysNoticeMapper;
import com.yxw.live_vod_boot.mqtt.MqttGateway;
import com.yxw.live_vod_boot.service.SysNoticeService;
import com.yxw.live_vod_boot.utils.JsonUtils;
import com.yxw.live_vod_boot.utils.PageUtils;
import com.yxw.live_vod_boot.vo.MqttInforSystemVO;
import com.yxw.live_vod_boot.vo.MqttNoticeVo;
import com.yxw.live_vod_boot.vo.SysNoticeInfoVo;
import com.yxw.live_vod_facade.enums.NoticeTypeEnum;
import com.yxw.yxnet_cd_center.common.constant.CommonConstant;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Future;

/**
 * 系统消息通知管理
 *
 * @author liuxin
 * @date 2023.11.15
 */
@Service
@Slf4j
public class SysNoticeServiceImpl extends ServiceImpl<SysNoticeMapper, YxSysNoticeEntity> implements SysNoticeService {


    @Autowired
    private MqttGateway mqttGateway;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private SysNoticeFeignClient sysNoticeFeignClient;

    /**
     * 发送审核系统消息-通用方法
     *
     * @param msgDto
     */
    @Override
//    @Async("common-executor")
    @Transactional(rollbackFor = Exception.class)
    public Future<BaseResult> sendNotice(SendInteractMsgDto msgDto) {
        //异常信息
        String errMsg = "";
        YxSysNoticeEntity yxSysNoticeEntity = null;
        NoticeTypeEnum type = msgDto.getType();
        //查询消息类型相关信息
        NoticeTypeQueryDto queryDto = new NoticeTypeQueryDto();
        queryDto.setNoticeTypeCode(type.getNoticeTypeCode());
        queryDto.setUseTypeCode(type.getUseTypeCode());
        queryDto.setStatus(1);
        BaseResult<PageVO<NoticeTypeVo>> baseResult = sysNoticeFeignClient.pageNoticeTypeList(queryDto);
        PageVO<NoticeTypeVo> data = baseResult.getData();
        if (null != data && null != data.getList() && !data.getList().isEmpty()) {
            yxSysNoticeEntity = new YxSysNoticeEntity();
            try {
                NoticeTypeVo typeVo = data.getList().get(0);
                //新增发送消息
                yxSysNoticeEntity.setNoticeTypeCode(typeVo.getNoticeTypeCode());
                yxSysNoticeEntity.setNoticeTypeName(typeVo.getUseTypeName());
                yxSysNoticeEntity.setUseTypeCode(typeVo.getUseTypeCode());
                yxSysNoticeEntity.setUseTypeName(typeVo.getUseTypeName());
                yxSysNoticeEntity.setCreateTime(new Date());
                yxSysNoticeEntity.setSendWay(CommonConstant.TWO);
                yxSysNoticeEntity.setReadFlag(0);
                yxSysNoticeEntity.setUserId(msgDto.getUserId());
                yxSysNoticeEntity.setUserName(msgDto.getUserName());
                yxSysNoticeEntity.setShopId(msgDto.getShopId());
                yxSysNoticeEntity.setShopName(msgDto.getShopName());
                yxSysNoticeEntity.setNoticeCategory(typeVo.getBelongType());
                yxSysNoticeEntity.setContent(typeVo.getContent());
                //有跳转的时候校验业务ID
                if (1 == typeVo.getDetailType()) {
                    if (StringUtils.isBlank(msgDto.getBussId())) {
                        throw new BaseException("有跳转时,业务ID不能为空");
                    }
                }
                yxSysNoticeEntity.setBussId(msgDto.getBussId());
                //推送消息
                MqttNoticeVo vo = new MqttNoticeVo();
                vo.setSysTime(new Date());
                vo.setReceiverId(null==msgDto.getShopId() ? msgDto.getUserId() : msgDto.getShopId());
                vo.setContent(typeVo.getContent());
                vo.setType(typeVo.getBelongType());
                mqttGateway.sendToMqtt(MqttTopicEnum.SYSTEM_NOTICE_TOPIC.getTopic() + vo.getReceiverId(), JsonUtils.toJson(vo));
                yxSysNoticeEntity.setStatus(CommonConstant.ONE);
            } catch (Exception e) {
                yxSysNoticeEntity.setStatus(CommonConstant.ZERO);
                log.error("发送消息失败=======================>>>>" + e.getMessage());
                errMsg = "发送消息失败" + e.getMessage();
            }
            //保存
            baseMapper.insert(yxSysNoticeEntity);
        }
        return new AsyncResult<>(BaseResult.doSuccess(yxSysNoticeEntity, errMsg));
    }

    @Async
    public BaseResult sendNoticeCustomNoticeType(SendInteractMsgDto msgDto, NoticeTypeVo typeVo) {
        //异常信息
        String errMsg = "";
        YxSysNoticeEntity yxSysNoticeEntity = new YxSysNoticeEntity();
        //NoticeTypeEnum type = msgDto.getType();
        //yxSysNoticeEntity = new YxSysNoticeEntity();
        try {
            //新增发送消息
            yxSysNoticeEntity.setNoticeTypeCode(typeVo.getNoticeTypeCode());
            yxSysNoticeEntity.setNoticeTypeName(typeVo.getUseTypeName());
            yxSysNoticeEntity.setUseTypeCode(typeVo.getUseTypeCode());
            yxSysNoticeEntity.setUseTypeName(typeVo.getUseTypeName());
            yxSysNoticeEntity.setCreateTime(new Date());
            yxSysNoticeEntity.setSendWay(CommonConstant.TWO);
            yxSysNoticeEntity.setReadFlag(0);
            yxSysNoticeEntity.setUserId(msgDto.getUserId());
            yxSysNoticeEntity.setUserName(msgDto.getUserName());
            yxSysNoticeEntity.setShopId(msgDto.getShopId());
            yxSysNoticeEntity.setShopName(msgDto.getShopName());
            yxSysNoticeEntity.setNoticeCategory(typeVo.getBelongType());
            yxSysNoticeEntity.setContent(typeVo.getContent());
            //有跳转的时候校验业务ID
            if (1 == typeVo.getDetailType()) {
                if (StringUtils.isBlank(msgDto.getBussId())) {
                    throw new BaseException("有跳转时,业务ID不能为空");
                }
            }
            yxSysNoticeEntity.setBussId(msgDto.getBussId());
            //推送消息
            MqttNoticeVo vo = new MqttNoticeVo();
            vo.setSysTime(new Date());
            vo.setReceiverId(null==msgDto.getShopId() ? msgDto.getUserId() : msgDto.getShopId());
            vo.setContent(typeVo.getContent());
            vo.setType(typeVo.getBelongType());
            mqttGateway.sendToMqtt(MqttTopicEnum.SYSTEM_NOTICE_TOPIC.getTopic() + vo.getReceiverId(), JsonUtils.toJson(vo));
            yxSysNoticeEntity.setStatus(CommonConstant.ONE);
        } catch (Exception e) {
            yxSysNoticeEntity.setStatus(CommonConstant.ZERO);
            log.error("发送消息失败=======================>>>>" + e.getMessage());
            errMsg = "发送消息失败" + e.getMessage();
        }
        //保存
        baseMapper.insert(yxSysNoticeEntity);

        return BaseResult.doSuccess(yxSysNoticeEntity, errMsg);
    }

    //@Override
    public BaseResult sendHomepageReview(ReviewExamineDTO dto, YxUploadSourceMaterialReviewEntity reviewEntity) {
        //异常信息
        String errMsg = "";
        YxSysNoticeEntity yxSysNoticeEntity = new YxSysNoticeEntity();
        try {
            //新增发送消息
            yxSysNoticeEntity.setNoticeTypeCode("1");
            yxSysNoticeEntity.setNoticeTypeName("店铺主页信息审核");
            String content = "";
            yxSysNoticeEntity.setContent(content);
            yxSysNoticeEntity.setCreateTime(new Date());
            yxSysNoticeEntity.setSendWay(CommonConstant.TWO);
            yxSysNoticeEntity.setReadFlag(0);
            yxSysNoticeEntity.setUserId(reviewEntity.getShopId());
            yxSysNoticeEntity.setUserName(reviewEntity.getShopName());
            if (1 == dto.getExamineStatus()) {
                content = "您的主页相关信息审核已通过";
            } else {
                content = "您的主页相关信息审核未通过:" + dto.getExamineDescribe();
            }
            //推送消息
            MqttInforSystemVO vo = new MqttInforSystemVO();
            vo.setContentType(content);
            vo.setMsgType("notification");
            vo.setContentType("text");
            mqttGateway.sendToMqtt(MqttTopicEnum.SYSTEM_NOTICE_TOPIC.getTopic() + reviewEntity.getShopId(), JsonUtils.toJson(vo));
            yxSysNoticeEntity.setStatus(CommonConstant.ONE);
        } catch (Exception e) {
            yxSysNoticeEntity.setStatus(CommonConstant.ZERO);
            log.error("发送消息失败=======================>>>>" + e.getMessage());
            errMsg = "发送消息失败" + e.getMessage();
        }
        //保存
        baseMapper.insert(yxSysNoticeEntity);
        return BaseResult.doSuccess(yxSysNoticeEntity, errMsg);
    }

    /**
     * 查询个人系统消息列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageVO<SysNoticeInfoVo> getNoticesByUserId(SysNoticeQueryDTO dto) {
        List<SysNoticeInfoVo> volist = new ArrayList<>();
        Page<YxSysNoticeEntity> page = new Page<>(dto.getCurrPage(), dto.getPageSize());
        LambdaQueryWrapper<YxSysNoticeEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null!=dto.getUserId(), YxSysNoticeEntity::getUserId, dto.getUserId())
                .eq(null!=dto.getShopId(), YxSysNoticeEntity::getShopId, dto.getShopId())
                .eq(true, YxSysNoticeEntity::getStatus, CommonConstant.ONE)
                .orderByDesc(true, YxSysNoticeEntity::getCreateTime);
        queryWrapper.eq(YxSysNoticeEntity::getNoticeCategory, 3);
        Page<YxSysNoticeEntity> pageEntity = baseMapper.selectPage(page, queryWrapper);
        List<YxSysNoticeEntity> noticeList = pageEntity.getRecords();
        if (null != noticeList && !noticeList.isEmpty()) {
            volist = BeanUtil.copyToList(noticeList, SysNoticeInfoVo.class);
        }
        return PageUtils.get(page, volist);
    }

    /**
     * 消息变更为已读
     *
     * @param noticeId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateNoticeStatus(Long noticeId) {
        LambdaUpdateWrapper<YxSysNoticeEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(true, YxSysNoticeEntity::getReadFlag, CommonConstant.ONE)
                .eq(true, YxSysNoticeEntity::getNoticeId, noticeId);
        baseMapper.update(null, updateWrapper);
    }


    /**
     * 发送互动消息/新朋友消息（普通消息）
     *
     * @param msgDto
     */
    @Override
//    @Async(value ="sendNoticeExecutor")
    public void sendNormalNotice(SendNormalMsgDto msgDto) {
        try {
            MqttNoticeVo vo = new MqttNoticeVo();
            vo.setSysTime(new Date());
            vo.setReceiverId(null==msgDto.getShopId() ? msgDto.getUserId() : msgDto.getShopId());
            String content = "";
            if (1 == msgDto.getType()) {
                content = "有新朋友关注了您";
            } else {
                content = "有人回复了您";
            }
            vo.setContent(content);
            vo.setType(msgDto.getType());
            mqttGateway.sendToMqtt(MqttTopicEnum.SYSTEM_NOTICE_TOPIC.getTopic() + vo.getReceiverId(), JsonUtils.toJson(vo));
        } catch (Exception e) {
            log.error("发送消息失败=======================>>>>" + e.getMessage());
        }
    }
}
